package jxc.servlet.sale;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.log.LogFactory;
import eu.log.Logger;

import jxc.base.helper.IdGenerator;
import jxc.base.helper.TimeGenerator;
import jxc.base.helper.UserAuthenticator;
import jxc.data.hibernate.dao.CustomerDAO;
import jxc.data.hibernate.dao.GoodsDAO;
import jxc.data.hibernate.dao.SalesbackDAO;
import jxc.data.hibernate.pojo.Customer;
import jxc.data.hibernate.pojo.Goods;
import jxc.data.hibernate.pojo.Salesback;

/**
 * 处理销售业务
 */
@WebServlet("/sale/return")
public class Return extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger logger=LogFactory.getLogger("销售");
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Return() {
        super();
    }


	/**
	 * 销售退货
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String customerName=request.getParameter("customer_name");
		String payType=request.getParameter("pay_type");
		String goodsList=request.getParameter("goods");
		List<Salesback> sales=resolveGoods(goodsList,customerName,payType,UserAuthenticator.getUser(request).getName());
		//写入
		SalesbackDAO dao=new SalesbackDAO();
		double total=0;
		for(Salesback sale:sales){
			dao.save(sale);
			total+=sale.getNumber()*sale.getPrice();
		}
		dao.commit();
		request.setAttribute("sales", sales);
		request.setAttribute("total", total);
		request.setAttribute("time", TimeGenerator.getTimeString());
		request.getRequestDispatcher("/sale/return.jsp").forward(request, response);
	}

	/**
	 * 解析页面商品列表，返回销售列表
	 */
	protected List<Salesback> resolveGoods(String goodsList,String customer,String payType,String username) throws IOException{
		List<Salesback> sales=new ArrayList<Salesback>();
		Goods good=null;
		Salesback sale=null;
		GoodsDAO gDao=new GoodsDAO();
		String id=null;
		String amount=null;
		String price=null;
		String[] goods=goodsList.split(";");
		String[] fields=null;
		for(String line:goods){
			fields=line.split("#");
			id=fields[0];
			amount=fields[1];
			price=fields[2];
			good=gDao.getById(id);
			if(good==null)
				continue;
			sale=new Salesback();
			sale.setId(IdGenerator.getSaleId());
			sale.setNumber(Integer.parseInt(amount));
			sale.setOperateperson(username);
			sale.setPaytype(payType);
			sale.setPrice(Float.parseFloat(price));
			sale.setSalesbacktime(new Date());
			sale.setTbGoods(good);
			sale.setTbCustomer(getCustomer(customer));
			sales.add(sale);
		}
		return sales;
	}
	
	/**
	 * 查找客户，如果不存在，新建一个
	 */
	protected Customer getCustomer(String name){
		CustomerDAO dao=new CustomerDAO();
		Customer customer=dao.getByName(name);
		if(customer==null){
			//新建
			customer=new Customer();
			customer.setCustomername(name);
			customer.setId(IdGenerator.getCustomerId());
			customer.setAvailable(1);
			dao.save(customer);
			dao.commit();
			return customer;
		}
		return customer;
	}
}
